<?php

declare(strict_types=1);

namespace app\backend\controller\crm;

use app\common\controller\Basic;
use app\common\service\crm\ContactsService;
use PHPMailer\PHPMailer\PHPMailer;
use think\api\Client;
use app\common\validate\crm\Contacts as ContactsValidate;
use think\facade\Cache;


/**
 * 联系人表 控制器
 * @author 吕玉冰
 * @date  2022-07-21
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class Contacts extends Basic
{

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        // 当前控制器服务实例化
        $this->service = new ContactsService();
    }

    /**
     * 列表
     */
    public function index()
    {
        if ($this->request->isGet()) {
            $data = input('param.');
            return json($this->service->_list($data));
        }
        return _jerr(1000);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            $this->_form_filter($data);
            $validate = new ContactsValidate();
            if (!$validate->check($data)) {
                return _err($validate->getError());
            }
            return json($this->service->saveForm($data));
        }
        if ($this->request->isGet()) {
            $data = [];
            return _jok('ok', $data);
        }
        return _jerr(1000);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id = input('id/d', 0);
        if ($id === 0) {
            return _jerr(1022);
        }
        if ($this->request->isPost()) {
            $data = input('param.');
            $this->_form_filter($data);
            $validate = new ContactsValidate();
            if (!$validate->check($data)) {
                return _err($validate->getError());
            }
            return json($this->service->saveForm($data));
        }
        if ($this->request->isGet()) {
            $data = $this->service->getInfoById($id);
            $this->service->_out_form_filter($data);
            return _jok('ok', $data);
        }
        return _jerr(1000);
    }

    /**
     * 添加编辑-表单数据处理
     */
    protected function _form_filter(&$data)
    {
        $data = rq_decode($data); // 前端已 encodeURIComponent 编码（最深二维数组） 后端需要解码
        $data["create_user_id"] = $this->user['id'];
        $data["create_user_name"] = $this->user['real_name'];
        $data["owner_user_id"] = $this->user['id'];
        $data["owner_user_name"] = $this->user['real_name'];
    }

    /**
     * 删除
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $id = input('id', '');
            if ($id === 0) {
                return _jerr(1002);
            }
            return json($this->service->_del($id));
        }
        return _jerr(1000);
    }

    /**
     * lvyubing
     */
    public function sendMessage()
    {
        if ($this->request->isPost()) {
            $client = new Client("fe3144765b22cba5ff1b2379031ae193");
            $result = $client->smsSend()
                ->withSignId('78')
                ->withTemplateId('8')
                ->withPhone('17349652680')
                ->withParams('{"code": "7865"}')
                ->request();
        }
    }


    /**
     * lvyubing
     * @return \json
     * @throws \PHPMailer\PHPMailer\Exception
     */
    public function sendEmail()
    {
        if ($this->request->isPost()) {
            $data = rq_decode(input('param.'));
            $mail = new PHPMailer(true);
            //Server settings
            //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->isSMTP();                                           //Send using SMTP
            $mail->Host = 'smtp.163.com';                     //Set the SMTP server to send through
            $mail->SMTPAuth = true;                                   //Enable SMTP authentication
            $mail->Username = 'lvyubingonly@163.com';                     //SMTP username
            $mail->Password = 'KRQPZHDUHJUSKZPR';                               //SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
            $mail->Port = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

            //Recipients
            $mail->setFrom('lvyubingonly@163.com', 'system');
            $mail->addAddress($data['to'], $data['relation_id_name']);     //Add a recipient
            //$mail->addAddress('lvyubingonly@126.com');               //Name is optional
            //      $mail->addReplyTo('354535316@qq.com', 'Information');
            //      $mail->addCC('354535316@qq.com');
            //      $mail->addBCC('354535316@qq.com');

            //附件
            //      $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
            //      $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $data['title'];
            $mail->Body = $data['content'];
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
            $result = $mail->send();
            if ($result === true) {
                return _jok('发送成功!', $data);
            } else {
                return _jerr($result->message);
            }
        }

    }

    public function getAll()
    {
        if ($this->request->isPost()) {
            if (Cache::get("contactsList")) {
                $list = Cache::get("contactsList");
                return _ok("获取成功1", $list);
            } else {
                $list = (new ContactsService())->getListAll($where = true, ['id' => 'asc'], ["name", "id"]);
                Cache::set("contactsList", $list, 300);
                $list = Cache::get("contactsList");
                return _ok("获取成功2", $list);
            }
        }
        return _jerr(1000);
    }

    public function getByCustomer()
    {
        if ($this->request->isPost()) {
            $customer_id = input('customer_id', '');
            $where = [];
            $where[] = ["customer_id", "=", $customer_id];
            $list = (new ContactsService())->getListAll($where, ['id' => 'asc'], ["name", "id"]);
            return _ok("获取成功2", $list);
        }
        return _jerr(1000);
    }


}
    